/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rtech.billing.pdf.conversion;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.rtech.billing.property.Constants;
import com.rtech.billing.property.PropertiesManager;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

/**
 *
 * @author rattank
 */
public class PDFGeneratorWithWatermark extends PDFGenerator {
    private  String  filePath = "" ;
    protected String waterMarkText = "";
    protected boolean isPageNumberInWatermark = false ;
    protected PdfTemplate total;
    protected BaseFont helv;
    protected Image image;
    protected PdfGState gstate;
    protected Color color;
    
	public void onOpenDocument(PdfWriter writer, Document document) {
		total = writer.getDirectContent().createTemplate(100, 100);
		total.setBoundingBox(new Rectangle(-20, -20, 100, 100));
		try {
			helv = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
					BaseFont.NOT_EMBEDDED);
			image = Image
					.getInstance(PropertiesManager.getInstance().getPropertyValue(Constants.PROPERTY_WATERMARK_FILE_PATH));
                        waterMarkText = PropertiesManager.getInstance().getPropertyValue(Constants.PROPERTY_WATERMARK_TEXT) ;
                        String temp = PropertiesManager.getInstance().getPropertyValue(Constants.PROPERTY_WATERMARK_PAGENUMBER) ;
                        if("true".equals(temp)){
                            this.isPageNumberInWatermark = true ; 
                        }
                } catch (Exception e) {
			throw new ExceptionConverter(e);
		}
		gstate = new PdfGState();
		gstate.setFillOpacity(0.3f);
		gstate.setStrokeOpacity(0.3f);
	}

	public void onStartPage(PdfWriter writer, Document document) {
		if (writer.getPageNumber() % 2 == 1) {
			color = Color.blue;
		} else {
			color = Color.red;
		}
	}

	public void onEndPage(PdfWriter writer, Document document) {
		PdfContentByte directcontent = writer.getDirectContent();
		directcontent.saveState();
		String text = "Page " + writer.getPageNumber() + " of ";
		float textBase = document.bottom() - 20;
		float textSize = helv.getWidthPoint(text, 12);
		directcontent.beginText();
		directcontent.setFontAndSize(helv, 12);
                float adjust = helv.getWidthPoint("0", 12);
                directcontent.setTextMatrix(document.right() - textSize - adjust,
                                textBase);
                directcontent.showText(text);
                directcontent.endText();
                directcontent.addTemplate(total, document.right() - adjust,
                                textBase);
		directcontent.restoreState();
		if(true){
                try {
			PdfContentByte contentunder = writer.getDirectContentUnder();
			contentunder.saveState();
			contentunder.setGState(gstate);
//			contentunder.addImage(image, image.getWidth() * 4, 0, 0, image
//					.getHeight() * 4, 120, 650);
			contentunder.addImage(image, image.getWidth() * 4, 0, 0, image
					.getHeight() * 4, 120, 650);
                        
			contentunder.setColorFill(CMYKColor.MAGENTA);
			contentunder.beginText();
			contentunder.setFontAndSize(helv, 48);
                        if(isPageNumberInWatermark){
                            contentunder.showTextAligned(Element.ALIGN_CENTER,
					waterMarkText + " " + writer.getPageNumber(), document
							.getPageSize().getWidth() / 2, document.getPageSize()
							.getHeight() / 2, 45);
                        }else{
                            contentunder.showTextAligned(Element.ALIGN_CENTER,
					waterMarkText , document
							.getPageSize().getWidth() / 2, document.getPageSize()
							.getHeight() / 2, 45);
                        }
			
			contentunder.endText();
			contentunder.restoreState();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
                }
	}

	public void onCloseDocument(PdfWriter writer, Document document) {
		total.beginText();
		total.setFontAndSize(helv, 12);
		total.setTextMatrix(0, 0);
		total.showText("" + (writer.getPageNumber() - 1));
		total.endText();
	}
        
    public String createPDF(String fileName , String fileContent , boolean headerRequired) {
        this.filePath = PropertiesManager.getInstance().getPropertyValue(Constants.PROPERTY_TARGET_FILE_PATH);
        PdfWriter writer;
        try {
            Document document = new Document();
            writer = PdfWriter.getInstance(document, new FileOutputStream( filePath + fileName));
            writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
            writer.setPageEvent(new PDFGeneratorWithWatermark());
            document.setMargins(36, 36, 36, 54);
            // step 3:
            document.open();
            if(headerRequired){
                String  headerString = getHeaderElement() ;
                StringReader header = new StringReader(headerString);
                List<Element> headerElements = HTMLWorker.parseToList(header, null);
                for (Element element : headerElements) {
                    document.add(element);
                }
                
            }
            StringReader  reader = new StringReader(fileContent );
            
            List<Element> elements = HTMLWorker.parseToList(reader, null);

            for (Element element : elements) {
                document.add(element);
            }
            document.close();
        } catch (DocumentException ex) {
            ex.printStackTrace();
        }catch (IOException ex) {
                ex.printStackTrace();
        }


        return filePath + fileName; 
    }

 
}
